// let shareUrl = `https://item.taobao.com/item.htm?id=${item.itemId}`

let shareUrl = 'https://item.taobao.com/item.htm?id=622435977623'
https: requestPrice(shareUrl, function (data) {
  if (data) {
    if (data.ok == 1 && data.single) {
      const lower = lowerMsgs(data.single)
      const detail = priceSummary(data)
      const tip = data.PriceRemark.Tip + '（仅供参考）'
      console.log(
        `${lower} ${tip}\n${detail}\n\n👉查看详情：http://tool.manmanbuy.com/historyLowest.aspx?url=${encodeURI(
          shareUrl
        )}`
      )
    }
    if (data.ok == 0 && data.msg.length > 0) {
      console.log(`⚠️ ${data.msg}`)
    }
  }
})

/**
 * 返回历史最低价
 * @param {Object} data 价格数据
 */
function lowerMsgs(data) {
  const lower = data.lowerPriceyh
  const lowerDate = dateFormat(data.lowerDateyh)
  const lowerMsg = '〽️历史最低到手价：¥' + String(lower) + `（${lowerDate}）`
  return lowerMsg
}

/**
 * 返回自定义时间格式
 * @param {String} cellval 时间数据
 */
function dateFormat(cellval) {
  const date = new Date(
    parseInt(cellval.replace('/Date(', '').replace(')/', ''), 10)
  )
  const month =
    date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1
  const currentDate =
    date.getDate() < 10 ? '0' + date.getDate() : date.getDate()
  return date.getFullYear() + '-' + month + '-' + currentDate
}

/**
 * 返回历史价格摘要
 * @param {Object} data 价格数据
 */
function priceSummary(data) {
  let summary = ''
  let listPriceDetail = data.PriceRemark.ListPriceDetail
  listPriceDetail.pop()
  let list = listPriceDetail.concat(historySummary(data.single))
  list.forEach((item, index) => {
    if (item.Name == '双11价格') {
      item.Name = '双十一价格'
    } else if (item.Name == '618价格') {
      item.Name = '六一八价格'
    } else if (item.Name == '30天最低价') {
      item.Name = '三十天最低'
    }
    summary += `\n${item.Name}   ${item.Price}   ${item.Date}   ${item.Difference}`
  })
  return summary
}

/**
 * 返回处理后的历史摘要数组
 * @param {Object} single 简洁数据
 */
function historySummary(single) {
  const rexMatch = /\[.*?\]/g
  const rexExec = /\[(.*),(.*),"(.*)".*\]/
  let currentPrice, lowest60, lowest180, lowest360
  let list = single.jiagequshiyh.match(rexMatch)
  list = list.reverse().slice(0, 360)
  list.forEach((item, index) => {
    if (item.length > 0) {
      const result = rexExec.exec(item)
      const dateUTC = new Date(eval(result[1]))
      const date = dateUTC.format('yyyy-MM-dd')
      let price = parseFloat(result[2])
      if (index == 0) {
        currentPrice = price
        lowest60 = {
          Name: '六十天最低',
          Price: `¥${String(price)}`,
          Date: date,
          Difference: difference(currentPrice, price),
          price
        }
        lowest180 = {
          Name: '一百八最低',
          Price: `¥${String(price)}`,
          Date: date,
          Difference: difference(currentPrice, price),
          price
        }
        lowest360 = {
          Name: '三百六最低',
          Price: `¥${String(price)}`,
          Date: date,
          Difference: difference(currentPrice, price),
          price
        }
      }
      if (index < 60 && price <= lowest60.price) {
        lowest60.price = price
        lowest60.Price = `¥${String(price)}`
        lowest60.Date = date
        lowest60.Difference = difference(currentPrice, price)
      }
      if (index < 180 && price <= lowest180.price) {
        lowest180.price = price
        lowest180.Price = `¥${String(price)}`
        lowest180.Date = date
        lowest180.Difference = difference(currentPrice, price)
      }
      if (index < 360 && price <= lowest360.price) {
        lowest360.price = price
        lowest360.Price = `¥${String(price)}`
        lowest360.Date = date
        lowest360.Difference = difference(currentPrice, price)
      }
    }
  })
  return [lowest60, lowest180, lowest360]
}

/**
 * 返回价格涨跌幅
 * @param {String} currentPrice 当前价格
 * @param {String} price 历史价格
 */
function difference(currentPrice, price) {
  let difference = sub(currentPrice, price)
  if (difference == 0) {
    return '-'
  } else {
    return `${difference > 0 ? '↑' : '↓'}${String(difference)}`
  }
}

function sub(arg1, arg2) {
  return add(arg1, -Number(arg2), arguments[2])
}

function add(arg1, arg2) {
  ;(arg1 = arg1.toString()), (arg2 = arg2.toString())
  var arg1Arr = arg1.split('.'),
    arg2Arr = arg2.split('.'),
    d1 = arg1Arr.length == 2 ? arg1Arr[1] : '',
    d2 = arg2Arr.length == 2 ? arg2Arr[1] : ''
  var maxLen = Math.max(d1.length, d2.length)
  var m = Math.pow(10, maxLen)
  var result = Number(((arg1 * m + arg2 * m) / m).toFixed(maxLen))
  var d = arguments[2]
  return typeof d === 'number' ? Number(result.toFixed(d)) : result
}

/**
 * 获取价格数据
 * @param {String} share_url 商品链接
 * @param {Function} callback 回调函数
 */
function requestPrice(share_url, callback) {
  const url =
    'https://apapia-history.manmanbuy.com/ChromeWidgetServices/WidgetServices.ashx'
  const body =
    'methodName=getHistoryTrend&p_url=' + encodeURIComponent(share_url)
  const httpRequest = new XMLHttpRequest()
  httpRequest.open('POST', url, true)
  httpRequest.setRequestHeader(
    'Content-type',
    'application/x-www-form-urlencoded;charset=utf-8'
  )
  console.log(body)
  httpRequest.send(body)
  /**
   * 获取数据后的处理程序
   */
  httpRequest.onreadystatechange = function () {
    //请求后的回调接口，可将请求成功后要执行的程序写在其中
    if (httpRequest.readyState == 4 && httpRequest.status == 200) {
      //验证请求是否发送成功
      var data = httpRequest.responseText //获取到服务端返回的数据
      console.log(data)
      document.write(data)
      callback(JSON.parse(data))
    }
  }
}

Array.prototype.insert = function (index, item) {
  this.splice(index, 0, item)
}

Date.prototype.format = function (fmt) {
  var o = {
    'y+': this.getFullYear(),
    'M+': this.getMonth() + 1,
    'd+': this.getDate(),
    'h+': this.getHours(),
    'm+': this.getMinutes(),
    's+': this.getSeconds(),
    'q+': Math.floor((this.getMonth() + 3) / 3),
    'S+': this.getMilliseconds()
  }
  for (var k in o) {
    if (new RegExp('(' + k + ')').test(fmt)) {
      if (k == 'y+') {
        fmt = fmt.replace(RegExp.$1, ('' + o[k]).substr(4 - RegExp.$1.length))
      } else if (k == 'S+') {
        var lens = RegExp.$1.length
        lens = lens == 1 ? 3 : lens
        fmt = fmt.replace(
          RegExp.$1,
          ('00' + o[k]).substr(('' + o[k]).length - 1, lens)
        )
      } else {
        fmt = fmt.replace(
          RegExp.$1,
          RegExp.$1.length == 1
            ? o[k]
            : ('00' + o[k]).substr(('' + o[k]).length)
        )
      }
    }
  }
  return fmt
}
